#pragma once
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
namespace Client
{
    class UdpClient
    {
    public:
        UdpClient(const std::string &serverip, const uint16_t &serverport)
            : _serverip(serverip), _serverport(serverport), _sockfd(-1), _quit(false)
        {
        }
        void initClient()
        {
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                std::cerr << "socket error: " << errno << " : " << strerror(errno) << std::endl;
                exit(2);
            }
            std::cout << "socket success : " << _sockfd << std::endl;
        }
        void run()
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());
            server.sin_port = htons(_serverport);
            std::string message;
            while (!_quit)
            {
                std::cout << "Please Enter# ";
                std::cin >> message;
                sendto(_sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
                char buffer[1024];
                struct sockaddr_in temp;
                socklen_t len = sizeof(temp);
                ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len);
                if (n > 0)
                {
                    buffer[n] = 0;
                }
                std::cout << buffer << std::endl;
            }
        }
        ~UdpClient()
        {
        }

    private:
        int _sockfd;
        std::string _serverip;
        uint16_t _serverport;
        bool _quit;
    };
}